package com.songcha.module_main.ui.activity.main

import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.os.Bundle
import android.os.Looper
import android.os.PersistableBundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentStatePagerAdapter
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.songcha.library_base.base.BaseFragment
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.BuildConfig
import com.songcha.library_business.LibraryBusinessApplication
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.config.VarConfig
import com.songcha.library_business.event.account.LoginSuccessEvent
import com.songcha.library_business.event.main.BottomNavigationReInitEvent
import com.songcha.library_business.event.account.LogoutEvent
import com.songcha.library_business.event.home.HomeInsertScreenAdvertEvent
import com.songcha.library_business.handler.home_dialog.AbsHomeDialog
import com.songcha.library_business.handler.home_dialog.CurrentTimeErrorDialog
import com.songcha.library_business.handler.home_dialog.NoNetWorkDialog
import com.songcha.library_business.handler.home_dialog.SqueezeAccountLoginDialog
import com.songcha.library_business.helper.AdvertHelper
import com.songcha.library_business.helper.permission.LocationPermissionHelper
import com.songcha.library_business.helper.UMengHelper
import com.songcha.library_business.helper.permission.PermissionResult
import com.songcha.library_business.helper.permission.WriteCalendarPermissionHelper
import com.songcha.library_business.proxy.main.ToAlmanacEvent
import com.songcha.library_business.proxy.main.ToHomeEvent
import com.songcha.library_business.proxy.main.ToMineEvent
import com.songcha.library_business.proxy.main.ToWeatherEvent
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.proxy.weather.WeatherManager
import com.songcha.library_business.ui.activity.BaseFontScaleMvvmActivity
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.LibraryCommon
import com.songcha.library_common.handler.AppExitTipHandler
import com.songcha.library_common.helper.SharedPreferenceHelper
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.view.BottomNavigationItemView
import com.songcha.library_common.ui.view.BottomNavigationView
import com.songcha.library_common.ui.view.CustomContainerLayout
import com.songcha.library_common.ui.view.MsgTipsView
import com.songcha.library_common.util.ColorUtil
import com.songcha.library_common.util.DateUtil
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.StatusBarUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.library_common.util.sp2px
import com.songcha.module_main.R
import com.songcha.module_main.databinding.MainActivityMainBinding
import com.songcha.module_main.ui.fragment.calendar.CalendarFragment
import com.songcha.module_main.ui.fragment.mine.MineFragment
import com.songcha.module_main.ui.fragment.qmy.QmyFragment
import com.songcha.module_main.ui.fragment.rank.RankFragment
import com.songcha.module_main.ui.fragment.tqa.TQAFragment
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import me.jessyan.autosize.AutoSize

import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.TimeUnit


@Route(path="/main/MainActivity")
class MainActivity : BaseMvvmActivity<MainViewModel, MainActivityMainBinding>(),BottomNavigationView.IOnBottomNavigationItemChangeListener
{
    //private lateinit var binding: AppActivityMainBinding

    val mFragments = mutableListOf<BaseFragment>(

    )

    override fun getLayoutId(): Int {
        return R.layout.main_activity_main
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun isDarkStatusBar(): Boolean {
        return false
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        initLogin()

        //TODO
        /*val trans = supportFragmentManager.beginTransaction()
        trans.replace(R.id.main_frag,QmyFragment())
        trans.commit()*/

        initTab()

        EventBus.getDefault().register(this)
    }

    private fun initLogin(){
        if(UserInfoManager.loginToken.isEmpty())
            viewModel.loginByDeviceId()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //LogUtil.log(System.currentTimeMillis(),savedInstanceState, tag = "main onCreate")
        if(savedInstanceState != null && !LibraryBusinessApplication.isInitApp()){
            BusinessJumpUtil.toSplashActivity(this,false)
            finish()
        }
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
        super.onSaveInstanceState(outState, outPersistentState)
        //LogUtil.log(System.currentTimeMillis(),outState, tag = "main onSaveInstanceState")
        //LogUtil.log(outState,System.currentTimeMillis(),tag = "main onSaveInstanceState")
    }

    override fun onRestoreInstanceState(
        savedInstanceState: Bundle?,
        persistentState: PersistableBundle?
    ) {
        super.onRestoreInstanceState(savedInstanceState, persistentState)
        //LogUtil.log(System.currentTimeMillis(),savedInstanceState, persistentState,tag = "main onRestoreInstanceState")
        //LogUtil.log(savedInstanceState,System.currentTimeMillis(),tag = "main onRestoreInstanceState")
    }

    private fun initTab(){
        val tqaFrag = TQAFragment()
        val bundle = Bundle()
        bundle.putString("url",VarConfig.TAQ_URL)
        tqaFrag.arguments = bundle

        mFragments.add(QmyFragment())
        mFragments.add(CalendarFragment())
        mFragments.add(tqaFrag)
        mFragments.add(RankFragment())
        mFragments.add(MineFragment())

        intent?.let {
            val isExit=it.getBooleanExtra("is_exit",false)
            if(isExit)
                finish()
        }

        val vp = databinding.mainNsvp
        vp.adapter=object: FragmentStatePagerAdapter(supportFragmentManager){
            override fun getCount(): Int {
                return mFragments.size
            }

            override fun getItem(position: Int): Fragment {
                return mFragments[position]
            }

        }

        val bnvItemList = mutableListOf<BottomNavigationItemView>()

        val bnvItemQmy = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"敲木鱼",R.mipmap.main_icon_bottom_tab_qmy_normal,R.mipmap.main_icon_bottom_tab_qmy_selected)
        }
        bnvItemQmy.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemQmy)

        val bnvItemCalendar = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"功德日历",R.mipmap.main_icon_bottom_tab_calendar_normal,R.mipmap.main_icon_bottom_tab_calendar_selected)
        }
        bnvItemCalendar.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemCalendar)

        val bnvItemTQA= BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"测一测",R.mipmap.main_icon_bottom_tab_tqa_normal,R.mipmap.main_icon_bottom_tab_tqa_selected)
        }
        bnvItemTQA.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemTQA)

        val bnvItemRank= BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"排行榜",R.mipmap.main_icon_bottom_tab_rank_normal,R.mipmap.main_icon_bottom_tab_rank_selected)
        }
        bnvItemRank.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemRank)

        val bnvItemMine = BottomNavigationItemView(this){p,b,v->
            return@BottomNavigationItemView getBottomTabView(p,b,v,"我的",R.mipmap.main_icon_bottom_tab_mine_normal,R.mipmap.main_icon_bottom_tab_mine_selected)
        }
        bnvItemMine.layoutParams =
            LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        bnvItemList.add(bnvItemMine)

        for(i in 0 until mFragments.size){
            val frag = mFragments[i]
            val bnvItem = bnvItemList[i]
            bnvItem.TAG = frag.TAG
            databinding.mainBnv.addView(bnvItem)
        }

        databinding.mainBnv.setOnBottomNavigationItemChangeListener(this)
        databinding.mainBnv.setViewPager(vp)

    }

    private fun getBottomTabView(p:LinearLayout,isSelect:Boolean,v: View?,title:String,
                                 iconNormalResId:Int,iconSelectedResId:Int
    ):View{
        if(v == null){
            val tab = LayoutInflater.from(p.context).inflate(R.layout.main_bottom_tab_item,p,false)
            val tvTitle = tab.findViewById<TextView>(R.id.main_tv_title)
            val ivIcon = tab.findViewById<ImageView>(R.id.main_iv_icon)
            tvTitle.text = title
            ivIcon.setImageResource(iconNormalResId)
            val mtv = tab.findViewById<MsgTipsView>(R.id.main_mtv)
            val hasSelect = SharedPreferenceHelper.getBoolean("bottom_tab","click_tqa")
            ViewHelper.setVisibility(title == "测一测" && !hasSelect,mtv)
            return tab
        }else{
            val tab = v!! as FrameLayout

            val tvTitle = tab.findViewById<TextView>(R.id.main_tv_title)
            val ivIcon = tab.findViewById<ImageView>(R.id.main_iv_icon)
            val mtv = tab.findViewById<MsgTipsView>(R.id.main_mtv)
            if(isSelect){
                ivIcon.setImageResource(iconSelectedResId)
                tvTitle.setTextColor(Color.parseColor("#A86436"))
                ViewHelper.setVisibility(false,mtv)
                if(title == "测一测")
                    SharedPreferenceHelper.setBoolean("bottom_tab","click_tqa",true)
            }else{
                ivIcon.setImageResource(iconNormalResId)
                tvTitle.setTextColor(Color.parseColor("#7A6D63"))
                val hasSelect = SharedPreferenceHelper.getBoolean("bottom_tab","click_tqa")
                ViewHelper.setVisibility(title == "测一测" && !hasSelect,mtv)
            }
            return v!!
        }
    }


    /**
     * exit app by indirect way
     */
    /*override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        finish()
    }*/

    @Subscribe
    fun onBottomNavigationReInit(event:BottomNavigationReInitEvent){
        for(i in mFragments.indices){
            val item = mFragments[i]
            if(item.TAG == event.tag){
                mFragments[i] = event.fragment
            }
        }
    }

    @Subscribe
    fun onToHome(event:ToHomeEvent){
        //databinding.mainBnv.select(0)
    }

    @Subscribe
    fun onToAlmanac(event:ToAlmanacEvent){
        //databinding.mainBnv.select(1)
    }

    @Subscribe
    fun onToWeather(event:ToWeatherEvent){
        //databinding.mainBnv.select(3)
    }

    @Subscribe
    fun onToMine(event:ToMineEvent){
        //databinding.mainBnv.select(4)
    }

    /*override fun onApplyWindowInsetsCall(v: View, insets: WindowInsetsCompat) {
        for(item in mFragments){
            (item as IOnApplyWindowInsetsCall).onApplyWindowInsetsCall(v,insets)
        }
    }*/

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        return AppExitTipHandler.handleOnKeyUp(this,keyCode){
            super.onKeyUp(keyCode, event)
        }
    }


    override fun onBottomNavigationItemChange(position: Int,tag:String) {
        for(frag in mFragments){
            if(frag is BottomNavigationView.IOnBottomNavigationItemChangeListener)
                frag.onBottomNavigationItemChange(position,tag)
        }
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onStop() {
        super.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun getResources(): Resources {
        return super.getResources()
    }
}